import fastifyPlugin from "fastify-plugin";
function biz(app, opt, next) {
  app.decorateReply(
    "createPagination",
    async function (model, query = {}, config = {}) {
      const { page = 1, pageSize = 10, t, ...rest } = this.request.query;
      const selfQuery = {
        ...rest,
        ...query,
      };

      const $and = Object.keys(selfQuery).map((k) => ({ [k]: selfQuery[k] }));

      const q = {};
      if ($and.length) {
        q.$and = $and;
      }

      const items = await model
        .find(q)
        .skip((page - 1) * pageSize)
        .limit(pageSize);

      if (config.onQuery) {
        items = config.onQuery(items);
      }

      const total = await model.find(selfQuery).countDocuments();
      return {
        items,
        page,
        pageSize,
        total,
      };
    }
  );
  next();
}
export default fastifyPlugin(biz);
